package com.nsi.controller.portal.nsi_post_bar;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.nsi.common.ServerResponse;
import com.nsi.enums.CheckStateEnum;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.MsgSecCheckJson;
import com.nsi.pojo.PostCategory;
import com.nsi.pojo.PostCategoryItem;
import com.nsi.pojo.PostCollect;
import com.nsi.pojo.transformObject.WechatSubmitPagesParm;
import com.nsi.service.*;
import com.nsi.util.Httpsrequest;
import com.nsi.util.PropertiesUtil;
import com.nsi.vo.nsi_shop_bar.PostDetailVO;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 帖子详情表 前台展示
 * </p>
 *
 * @author Luo Zhen
 * @since 2019-12-16
 */
@Controller
@RequestMapping("/postItem/")
@Api(value = "/postItem/", description = "新学说贴吧——(前台)贴吧详情页")
@Slf4j
public class PostCategoryItemController {

    private static final Integer SHARE_INTEGRAL = 3;

    private static final Integer HOT_COUNT = 3;

    private static final String TOKEN_PREFIX_SIKU = "token_miniProgramSiku";

    private static final String TOKEN_PREFIX_PITAYA = "token_miniProgramPitaya";

    @Autowired
    private PostCategoryService postCategoryService;
    @Autowired
    private PostCategoryItemService postCategoryItemService;
    @Autowired
    private PostCountCommonService postCountCommonService;
    @Autowired
    private PostCollectService postCollectService;
    @Autowired
    private MsgCheckService msgCheckService;
    @Autowired
    private CommunityUserService communityUserService;
    @Autowired
    private IFileService iFileService;


    /**
     * 发布帖子
     *
     * @param postCategory
     * @return
     */
    @RequestMapping(value = "add.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加帖子方法", httpMethod = "POST")
    public ServerResponse addPostCategory(PostCategoryItem postCategory) {
        postCategoryItemService.savePostCategoryItem(postCategory);
        //增加发帖用户积分 5分
        communityUserService.AddScore(5, postCategory.getOpenId());

        return ServerResponse.createBySuccessMessage("添加帖子成功");
    }

    /**
     * 个人页面——编辑发布帖子
     *
     * @param postCategory
     * @return
     */
    @RequestMapping(value = "update.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改方法", httpMethod = "POST")
    public ServerResponse updatePostCategory(PostCategoryItem postCategory) {
        if (postCategory.getItemId() == null) {
            return ServerResponse.createBySuccessMessage("参数不合法");
        }
        postCategory.setIsCheck(CheckStateEnum.IN_REVIEW.getCode());
        postCategoryItemService.updateById(postCategory);
        return ServerResponse.createBySuccess();
    }

    /**
     * 根据帖子Id返回详情
     *
     * @param itemId
     * @return
     */
    @RequestMapping(value = "detail.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id返回详情", httpMethod = "GET")
    public ServerResponse findByCategoryId(Integer itemId) {
        PostCategoryItem postCategory = postCategoryItemService.selectById(itemId);
        if (postCategory == null) {
            throw new NsiOperationException("该帖子不存在");
        }
        // 获取类目名称
        if (postCategory.getPostType() != null) {
            String[] categoryArray = postCategory.getPostType().split(";");
            List<String> categoryList = Arrays.asList(categoryArray);
            postCategory.setCategoryName(categoryList);
        }

        // 添加观看数
        postCountCommonService.addWatchNum(itemId);
        // 返回帖子热度最高前十条
        List<PostCategoryItem> categoryItemList = postCategoryItemService.selectList(
                new EntityWrapper<PostCategoryItem>()
                        .eq("is_check", CheckStateEnum.IN_APPROVE.getCode())
                        .orderBy("watch_num", false)
                        .last("limit 10")
        );
        // 打乱
        Collections.shuffle(categoryItemList);
        // 取最热随机三条
        List<PostCategoryItem> hotList = categoryItemList.stream()
                .limit(HOT_COUNT)
                .collect(Collectors.toList());

        PostDetailVO detailVO = new PostDetailVO();
        detailVO.setPostCategoryItem(postCategory);
        detailVO.setPostCategoryItemList(hotList);

        return ServerResponse.createBySuccess(detailVO);
    }

    /**
     * 获取子类类目列表
     *
     * @return
     */
    @RequestMapping(value = "find_category_item.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取子类类目列表", httpMethod = "GET")
    public ServerResponse findCategoryItem() {
        List<PostCategory> categoryList = postCategoryService.findCategoryList();
        return ServerResponse.createBySuccess(categoryList);
    }

    /**
     * 添加分享
     *
     * @param itemId
     * @return
     */
    @RequestMapping(value = "add_share_num.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分享功能", httpMethod = "GET")
    public ServerResponse addShareNum(Integer itemId) {
        // 帖子添加分享数
        postCountCommonService.addShareNum(itemId);

        // 添加积分
        PostCategoryItem postCategoryItem = postCategoryItemService.selectById(itemId);
        communityUserService.AddScore(SHARE_INTEGRAL, postCategoryItem.getOpenId());
        return ServerResponse.createBySuccess();
    }

    /**
     * 验证是否收藏
     *
     * @param openId
     * @param itemId
     * @return
     */
    @RequestMapping(value = "find_is_collect.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "验证是否收藏", httpMethod = "POST")
    public ServerResponse findIsCollect(@RequestParam("openId") String openId,
                                        @RequestParam("itemId") Integer itemId) {
        if (StringUtils.isEmpty(openId) || itemId == null) {
            throw new NsiOperationException("参数不合法");
        }
        int result = postCollectService.findIsCollect(openId, itemId);
        if (result > 0) {
            throw new NsiOperationException("用户已收藏");
        }
        return ServerResponse.createBySuccessMessage("用户未收藏");
    }

    /**
     * 取消收藏
     *
     * @param openId
     * @return
     */
    @RequestMapping(value = "collect_delete.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "取消收藏", httpMethod = "POST")
    public ServerResponse myCollect(@RequestParam("itemId") Integer itemId,
                                    @RequestParam("openId") String openId) {
        if (StringUtils.isEmpty(openId) || itemId == null) {
            throw new NsiOperationException("参数不合法");
        }
        postCollectService.delete(
                new EntityWrapper<PostCollect>()
                        .eq("open_id", openId)
                        .eq("item_id", itemId)
        );
        return ServerResponse.createBySuccessMessage("取消收藏成功");
    }

    /**
     * 收藏功能
     *
     * @param itemId
     * @return
     */
    @RequestMapping(value = "add_collect_num.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "收藏功能", httpMethod = "POST")
    public ServerResponse addCollectNum(@RequestParam("openId") String openId,
                                        @RequestParam("itemId") Integer itemId) {
        if (StringUtils.isEmpty(openId) || itemId == null) {
            throw new NsiOperationException("参数不合法");
        }
        // 添加用户和帖子关联
        PostCollect collect = new PostCollect();
        collect.setOpenId(openId);
        collect.setItemId(itemId);

        postCollectService.insert(collect);
        // 添加帖子收藏数
        postCountCommonService.addCollectNum(itemId);

        return ServerResponse.createBySuccessMessage("收藏成功");
    }

    /**
     * 内容校验(包括文章和评论)
     *
     * @param content
     * @param type    1-火龙果 2-四库全书
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "msg_sec_check.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "内容校验", httpMethod = "GET")
    public ServerResponse msgSecCheck(@RequestParam(value = "content", defaultValue = "", required = false) String content,
                                      @RequestParam(value = "type", defaultValue = "1", required = false) Integer type) throws Exception {
        // 校验内容是否为空
        if (StringUtils.isEmpty(content)) {
            throw new NsiOperationException("参数不合法");
        }
        String appId, appSecrey, TOKEN_PREFIX;
        if (type == 1) {
            // 获取access_token
            appId = PropertiesUtil.getProperty("miniProgram.pitaya.appid");
            appSecrey = PropertiesUtil.getProperty("miniProgram.pitaya.appSecret");
            TOKEN_PREFIX = TOKEN_PREFIX_PITAYA;
        } else {
            appId = PropertiesUtil.getProperty("miniProgram.siku.appid");
            appSecrey = PropertiesUtil.getProperty("miniProgram.siku.appSecret");
            TOKEN_PREFIX = TOKEN_PREFIX_SIKU;
        }

        String accessToken = msgCheckService.getToken(appId, appSecrey, TOKEN_PREFIX);
        // 拼接参数发至微信后台
        return msgCheckService.msgSecCheck(accessToken, content);

    }


    /**
     * 测试---内容校验(包括文章和评论)
     *
     * @param content
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "msg_sec_check02.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试---内容校验", httpMethod = "GET")
    public ServerResponse msgSecCheck02(@RequestParam(value = "content", defaultValue = "", required = false) String content) throws Exception {
        String accessToken = "31_AzZVX-T9PsUshEmbGolywHAV5qxbOIyQ-8fFRJuEmplEFqZlxFPbKxm9OnUYEXJSIxoMQYb3Kxw0TuymjaiDqcD5zgQBfqcGXoL4-Mcx-qk7eJCyLnOpTiR0QE4_Fg0DVeMKqsfNsbQX4SDhLIWhAFAYVJ";
        // 拼接参数发至微信后台
        return msgCheckService.msgSecCheck(accessToken, content);

    }


    @RequestMapping(value = "/PagePush.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "帖子推送,微信SEO方法", httpMethod = "POST")
    public ServerResponse PagePush(@RequestParam("id") int id) throws Exception {

        // 获取access_token
        String appId = PropertiesUtil.getProperty("miniProgram.pitaya.appid");
        String appSecrey = PropertiesUtil.getProperty("miniProgram.pitaya.appSecret");
        String accessToken = msgCheckService.getToken(appId, appSecrey, TOKEN_PREFIX_PITAYA);

        //封装发送请求参数
        String url = "https://api.weixin.qq.com/wxa/search/wxaapi_submitpages?access_token=" + accessToken;
        WechatSubmitPagesParm pagesParm = new WechatSubmitPagesParm();
        pagesParm.setPath("pages/hotDetails/hotDetails.html");
        pagesParm.setQuery("id=" + id);

        List<WechatSubmitPagesParm> list = new ArrayList<>();
        list.add(pagesParm);

        Map<String, Object> map = new HashMap<>();
        map.put("pages", list);

        Gson gson = new Gson();
        String parm = gson.toJson(map);
        System.out.println("parm:" + parm);
//        发送请求
        String resultString = Httpsrequest.httpsRequest(url, "POST", parm);
        System.out.println(resultString);
        MsgSecCheckJson msgSecCheckJson = gson.fromJson(resultString, MsgSecCheckJson.class);
        return ServerResponse.createBySuccess("success", msgSecCheckJson);
    }

    /**
     * 文章附件上传
     *
     * @param file
     * @param type
     * @return
     */
    @RequestMapping(value = "/upfile.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "附件上传", httpMethod = "POST")
    public ServerResponse uploadResume(@RequestParam(value = "file") MultipartFile file,
                                       @RequestParam(value = "type") String type) {
        String fileName = file.getOriginalFilename();
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String newFileName = System.currentTimeMillis() + "." + fileExtensionName;
        newFileName = iFileService.uploadResume(file, type, newFileName);
        String url = PropertiesUtil.getProperty("aliyun.image.url") + type + newFileName;

        Map resultMap = Maps.newHashMap();
        resultMap.put("uri", newFileName);
        resultMap.put("url", url);
        return ServerResponse.createBySuccess(resultMap);
    }
}
